package ru.hh.school.persistence;

import ru.hh.school.util.BlockingQueue;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import static ru.hh.school.Constants.DELAY_BETWEEN_ATTEMPTS_TO_RECONNECT_TO_DB;

public class ConnectionPool {
    private final int maxSize;
    private final String dbUrl;
    private final BlockingQueue<Connection> connections;

    public ConnectionPool(int maxSize, String dbUrl) throws SQLException {
        this.maxSize = maxSize;
        this.dbUrl = dbUrl;
        this.connections = new BlockingQueue<Connection>(maxSize);
        initConnections();
    }

    private void initConnections() throws SQLException {
        for (int i = 0; i < maxSize; i++) {
            final Connection connection = DriverManager.getConnection(dbUrl);
            this.connections.add(connection);
        }
    }

    public ConnectionFromPool getConnection() throws InterruptedException, SQLException {
        Connection connection = connections.take();
        while (!connection.isValid(0)) {
            connection = DriverManager.getConnection(dbUrl);
            Thread.sleep(DELAY_BETWEEN_ATTEMPTS_TO_RECONNECT_TO_DB);
        }
        return new ConnectionFromPool(connection, this);
    }

    public void freeConnection(Connection connection) {
        connections.add(connection);
    }
}